package cn.itsource.basic.service.impl;


import cn.itsource.basic.config.BussinessException;
import cn.itsource.basic.constant.BaseConstant;
import cn.itsource.basic.dto.AccountLoginDto;
import cn.itsource.basic.dto.WechatLoginDto;
import cn.itsource.basic.jwt.JwtUtils;
import cn.itsource.basic.jwt.RsaUtils;
import cn.itsource.basic.jwt.UserInfo;
import cn.itsource.basic.service.ILoginService;
import cn.itsource.basic.util.AjaxResult;
import cn.itsource.basic.util.HttpUtil;
import cn.itsource.basic.util.MD5Utils;
import cn.itsource.basic.util.StrUtils;
import cn.itsource.system.domain.Menu;
import cn.itsource.system.mapper.MenuMapper;
import cn.itsource.system.mapper.PermissionMapper;
import cn.itsource.user.domain.Logininfo;
import cn.itsource.user.domain.User;
import cn.itsource.user.domain.Wxuser;
import cn.itsource.user.mapper.LogininfoMapper;
import cn.itsource.user.mapper.UserMapper;
import cn.itsource.user.mapper.WxuserMapper;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.security.PrivateKey;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements ILoginService {


    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private WxuserMapper wxuserMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private MenuMapper menuMapper;

    @Value("${jwt.rsa.pri}")
    private String privateRsaKey;

    /**
     * 账号密码登陆
     *
     * @param dto
     */
    @Override
    public Map<String, Object> accountLogin(AccountLoginDto dto) {
        // 判断非空
        // 判断账号是否存在 loginifo
        Logininfo logininfo = logininfoMapper.findByUsername(dto.getUsername(), dto.getType());
        if (null == logininfo) {
            throw new BussinessException("账号或者密码错误！");
        }
        // 判断密码是否正确
        String encrypPassword = MD5Utils.encrypByMd5(logininfo.getSalt() + dto.getPassword());
        if (StringUtils.isBlank(encrypPassword) || !encrypPassword.equals(logininfo.getPassword())) {
            throw new BussinessException("账号或者密码错误！");
        }
        // 将token 和logininfo添加到redis中
        return getMap(logininfo);
    }

    private Map<String, Object> getMap(Logininfo logininfo) {
       // 使用jwt方案
        PrivateKey privateKey = RsaUtils.getPrivateKey(JwtUtils.class.getClassLoader().getResource(privateRsaKey)
                .getFile());
        Map<String, Object> hashMap = new HashMap<String, Object>();
        UserInfo user = new UserInfo();
        user.setLogininfo(logininfo);
        if (0 == logininfo.getType()){
            // 如果是后端 那么我们需要将权限放到token中
            // 菜单权限
            List<String> permissions = permissionMapper.findByLogininfoId(logininfo.getId());
            // 按钮权限
            List<Menu> menus = menuMapper.findByLogininfoId(logininfo.getId());
            user.setPermissions(permissions);
            user.setMenus(menus);
            hashMap.put("permissions", permissions);
            hashMap.put("menus", menus);
        }
        String token = JwtUtils.generateTokenExpireInMinutes(user, privateKey, 1440);
        // 将logininfo敏感字段置空
        logininfo.setPassword("");
        logininfo.setSalt("");
        logininfo.setPhone("");
        // 返回给前端
        hashMap.put("token", token);
        hashMap.put("logininfo", logininfo);
        return hashMap;
    }



//    private Map<String, Object> getMap(Logininfo logininfo) {
//        String token = UUID.randomUUID().toString();
//        redisTemplate.opsForValue().set(token, logininfo, 30, TimeUnit.MINUTES);
//        // 将logininfo敏感字段置空
//        logininfo.setPassword("");
//        logininfo.setSalt("");
//        logininfo.setPhone("");
//        // 返回给前端
//        Map<String, Object> hashMap = new HashMap<String, Object>() {{
//            put("token", token);
//            put("logininfo", logininfo);
//        }};
//        return hashMap;
//    }

    /**
     * 微信扫码登陆
     *
     * @param dto
     * @return
     */
    @Override
    public AjaxResult wechatLogin(WechatLoginDto dto) {
        // 验证参数
        if (StringUtils.isBlank(dto.getCode())) {
            throw new BussinessException("参数不能为空！");
        }
        // 根据code调用微信接口获取token和openid
        Pair<String, String> pair = this.getOpenidAndToken(dto.getCode());
        // 根据openId 去wx_user查询是否有数据
        Wxuser wxuser = wxuserMapper.findByOpenid(pair.getRight());
        if (null != wxuser && null != wxuser.getUserId()) {
            // 这个人之前登陆过 已经绑定过了 直接直接登陆
            // 返给前端 token logininfo
            Logininfo logininfo = logininfoMapper.findByUserId(wxuser.getUserId());
            Map<String, Object> map = getMap(logininfo);
            return AjaxResult.me().success(map);
        }
        // 当前人没有绑定
        StringBuffer sb = new StringBuffer()
                .append("?accessToken=")
                .append(pair.getLeft())
                .append("&openId=").append(pair.getRight());
        return AjaxResult.me().fail("nobinder").setResultObj(sb);
    }

    /**
     * 微信登陆绑定
     *
     * @param dto
     */
    @Override
    public Map<String,Object> wechatBinder(WechatLoginDto dto) {
        // 校验参数非空
        // 校验验证码是否正确
        this.verifySmsCode(dto);
        // 调用微信接口 获取用户信息
        String url = String.format(BaseConstant.WxLoginCons.WX_LOGIN_USER_INFO,dto.getAccessToken(),
                dto.getOpenId());
        String str = HttpUtil.httpGet(url);
        // json字符串转成 我们的实体
        Wxuser wxuser = JSONObject.parseObject(str, Wxuser.class);
        // 存
        // 查一下user有没有 没有的话存三张表 有的话存一张表
        User user = userMapper.findByPhone(dto.getPhone());
        Logininfo logininfo = new Logininfo();
        if (null == user){
            // 初始化user对象
            user =  initUser(dto);
            // 初始化logininfo对象
            logininfo =  initLogininfo(user);
            // 保存 logininfo
            logininfoMapper.add(logininfo);
            // 保存user
            user.setLogininfoId(logininfo.getId());
            userMapper.add(user);
        }else {
            // 获取logininfo对象
            logininfo = logininfoMapper.findByUserId(user.getId());
        }
        wxuser.setUserId(user.getId());
        wxuserMapper.add(wxuser);
        // 保存wxuser
        return getMap(logininfo);
    }

    private Logininfo initLogininfo(User user){
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user, logininfo);
        logininfo.setType(1);
        return logininfo;
    }

    private User initUser(WechatLoginDto dto){
        // 盐值
        String salt = StrUtils.getComplexRandomString(32);
        // 密码
        String password =salt + "1";
        System.out.println(password);
        String encryPwd = MD5Utils.encrypByMd5(password);
        return User
                .builder()
                .username(dto.getPhone())
                .phone(dto.getPhone())
                .salt(salt)
                .password(encryPwd)
                .state(1)
                .createtime(new Date())
                .build();
    }



    private void verifySmsCode(WechatLoginDto dto) {
        String redisSmsCode = (String) redisTemplate.opsForValue().get(
                String.format(BaseConstant.VerfityCodeCons.BINDER_SMSCODE_PHONE, dto.getPhone()));
        if (StringUtils.isBlank(redisSmsCode)) {
            throw new BussinessException("验证码错误！");
        }
        String smsCode = redisSmsCode.split(":")[0];
        if (!smsCode.equals(dto.getVerifyCode())) {
            throw new BussinessException("验证码错误！");
        }
    }

    // 通过code获取openid 和token
    private Pair<String, String> getOpenidAndToken(String code) {
        String tokenUrl = String.format(BaseConstant.WxLoginCons.WX_LOGIN_TOKEN_URL
                , BaseConstant.WxLoginCons.WX_LOGIN_APPID, BaseConstant.WxLoginCons.WX_LOGIN_SECRET
                , code);
        String str = HttpUtil.httpGet(tokenUrl);
        // 将json字符串转成json对象
        JSONObject jsonObject = JSONObject.parseObject(str);
        String accessToken = jsonObject.getString("access_token");
        String openid = jsonObject.getString("openid");
        // map 对象 集合 Pair
        return Pair.of(accessToken, openid);
    }
}
